package com.okok.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.common.ActionResult;
import com.common.Const;
import com.common.springside.Digests;
import com.common.springside.Encodes;
import com.entity.myInterface.RoleRepository;
import com.entity.myInterface.UserRepository;
import com.entity.paging.UserSearchCondition;
import com.okok.entity.User;
import com.shiro.entity.Role;
import com.shiro.entity.ShiroUser;
import com.shiro.services.AbstractService;
import com.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;



@Service
public class UserService extends AbstractService {
	private static Logger logger = LoggerFactory.getLogger(UserService.class);

	public static final int HASH_INTERATIONS = 1024;

	private static final int SALT_SIZE = 8;

	@Autowired
	UserRepository userRepository;

	@Autowired
	RoleRepository roleRepository;
	





	public List<User> search(int pageNo) {
		return userRepository.findAll();
	}

	public User findOne(String id) {
		return  this.userRepository.findByIdd(id);
	}
	
	/**
	 * 
	 * @Description:删除
	 * @param id
	 * @Author wendel
	 * @Date:2017年3月15日
	 */
	public void deleteByCurrentUser(String id) {
		userRepository.delete(id, getCurrentUserName());
	}

	public List<User> findBy(String username, String phone) {
		return this.userRepository.findBy(username, phone);
	}

	public Page<User> search(int pageNo, int pageSize, String condition, String app) {
		return this.userRepository.search(pageNo, pageSize, condition, app);
	}

	public User save(User user) {
		return this.userRepository.save(user);
	}

	public ActionResult save(String id, String loginName, String name,String contact, String phone, String roles,
			String email, String qqService) {
		User item = this.findOne(id);
		if (null == item) {
			item = new User();
			// 设置初始密码为123123
			item.setPlainPassword("123123");
			// 设定安全的密码，生成随机的salt并经过1024次
			entryptPassword(item);

			item.setCreator(getCurrentUser().getLoginName());
		}

		Boolean roleAdmin = false;
		Role ro = roleRepository.findByCode("admin");

		// 为角色设置权限
		if (StringUtils.isNotBlank(roles)) {
			String arrays[] = roles.split(",");
			List<Role> list = new ArrayList<Role>();
			for (String itemId : arrays) {
				if (itemId.equals(ro.getId())) {
					roleAdmin = true;
				}
				Role role = new Role(itemId);
				list.add(role);
			}
			if (!roleAdmin) {
				list.add(new Role(ro.getId()));
			}
			item.setRoles(list);
		} else {
			List<Role> list = new ArrayList<Role>();
			Role role = new Role(ro.getId());
			list.add(role);
			item.setRoles(list);
		}
		// 保存邮箱

		item.setLoginName(loginName);
		item.setName(name);
		item.setModifyDate(DateUtil.getNowDateTime());
		item.setModifier(getCurrentUser().getLoginName());

		logger.info(" save the user ");
		userRepository.save(item);

		return new ActionResult("", Const._INT_TRUE, "", Const._OK_SAVE, "");
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setLoginPwd(Encodes.encodeHex(hashPassword));
	}

	/**
	 * 逻辑删除
	 * 
	 * @param id
	 */
	public User delete(String id) {
		User item = findOne(id);
		item.setDelflag(true);

		return this.userRepository.save(item);
	}

	/**
	 * 查询当前登录用户的所有信息
	 * 
	 * @return
	 */
	public User findById() {
		return userRepository.findByIdd(getCurrentUser().getId());
	}

	public User findById(String id) {
		return userRepository.findByIdd(id);
	}





	/**
	 * 查询 用户
	 * @author larry(补充)
	 * @date 2017年5月23日
	 * @param usc
	 * @return
	 */
	public Page<User> findByPage(UserSearchCondition usc) {
		List<String> userIds = new ArrayList<String>();
		usc.setUserIds(userIds);
		Role role = roleRepository.findByCode(usc.getRoleCode());
		if (role == null) {
			return null;
		}
		usc.setRoleId(role.getId());
		return userRepository.findByPage(usc);
	}

	/**
	 * 判断用户是否为管理员 为管理员则返回true
	 * 
	 * @return
	 */
	public Boolean checkIsAdmin() {
		User user = userRepository.findByIdd(getCurrentUser().getId());
		List<Role> roles = user.getRoles();
		if (roles == null) {
			return false;
		}
		for (Role role : roles) {
			if (role.getCode().equals("admin")) {
				return true;
			}
		}
		return false;
	}

	public User findByMobilPhone(String mobilPhone) {
		return this.userRepository.findByMobilPhone(mobilPhone);
	}

	/**
	 * 根据用户帐号进行查询
	 * 
	 * @param loginName
	 * @return
	 */
	public User findByLoginName(String loginName) {
		return this.userRepository.findByLoginName(loginName);
	}





	public void savedesc(String id, String desc) {
		userRepository.updateDesc(id, desc, getCurrentUser().getLoginName());
	}


	/**
	 * 根据用户id修改linkTimeStamp
	 * 
	 * @param id
	 * @param linkTimeStamp
	 * @param currentUserName
	 */
	public void updateTimeStampById(String id, String linkTimeStamp, String currentUserName) {
		userRepository.updateTimeStampById(id, linkTimeStamp, currentUserName);
	}

	/**
	 * 根据用户id对用户角色进行修改
	 * 
	 * @param roles
	 * @param id
	 */
	public void updateRolesById(List<Role> roles, String id) {
		userRepository.updateRolesById(roles, id, getCurrentUserName());
	}
	
	public List<User> findByRoleCode(String code) {
		Role role = roleRepository.findByCode(code);
		if(role == null){
			return null;
		}
		return userRepository.findByRoleId(role.getId());
	}
	

	public ShiroUser getUser(){
		ShiroUser user = getCurrentUser();
		return user;
	}
	
	/**
	 * 检查当前用户的认证是否一个是通过的状态
	 * @return
	 */
	public boolean checkAuthStatus() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.hasRole("certUser")) {
			return true;
		}else {
			return false;
		}
	}


	
	 /**
	 * 模糊查询登陆名
	 * @author larry
	 * @date 2017年6月22日
	 * @param loginName
	 * @return
	 */
/*
	public List<User> findByLikeLoginName(String loginName){
		return userRepository.findByLikeLoginName(loginName);
	}
*/

	

}
